import React, { useState, useEffect } from 'react';

// 动画递增到目标数字
export default function CountUp({
    num, // 最终显示的数字
    delay = 1200, // 动画时间
    className,
}) {
    const [crValue, setCrValue] = useState((num * 33) / delay);
    const [start, setStart] = useState(0);

    useEffect(() => {
        function step(timestamp) {
            const randomTime = Math.random() * 5;
            const persent = (timestamp - start + randomTime) / delay;
            const newValue = Math.min(Math.ceil(num * persent), num);
            if (!start) {
                setStart(timestamp);
            } else if (timestamp - start <= delay) {
                window.requestAnimationFrame(step);
                setCrValue(Math.ceil(newValue));
            } else {
                setCrValue(num);
            }
        }
        if (window.requestAnimationFrame) {
            window.requestAnimationFrame(step);
        } else {
            console.error('浏览器暂不支持 window.requestAnimationFrame');
            setCrValue(num);
        }
    }, [num, start]);

    if (delay < 34) {
        console.error('动画时间这么短，我很难办啊');
        return null;
    }

    return <span className={className}>{WPT.Util.formatNumber(crValue, 0)}</span>;
}
